import cv2
import numpy as np
from PIL import Image

# 读取原图
image_0 = cv2.imread("hanzi1.jpg")
# 将原图转换为灰度图像
image_1 = cv2.cvtColor(image_0, cv2.COLOR_BGR2GRAY)
# 保存灰度图像
cv2.imwrite('image_1.jpg', image_1)

# 将灰度图image_1阈值200处理转换为二值图
_, image_2 = cv2.threshold(image_1, 90, 255, cv2.THRESH_BINARY)
# 反转
image_2 = np.bitwise_not(image_2)
# 保存二值图像
cv2.imwrite('image_2.jpg', image_2)

# 进行腐蚀操作去除噪点
image_2 = cv2.imread('image_2.jpg', cv2.IMREAD_GRAYSCALE)
# 创建的5*5的十字形结构元素
kernel = np.array([[0,0,1,0,0],
                   [0,1,1,1,0],
                   [1,1,1,1,1],
                   [0,1,1,1,0],
                   [0,0,1,0,0]], dtype=np.uint8)
# 进行腐蚀操作，迭代3次增强腐蚀效果
image_3 = cv2.erode(image_2, kernel, iterations=2)
# 保存腐蚀后的图像
cv2.imwrite('image_3.jpg', image_3)

#进行膨胀操作突出图像特征
# 用3*3的十字形结构元素进行膨胀操作
kernel = np.array([[0,1,0],
                   [1,1,1],
                   [0,1,0]], dtype=np.uint8)
image_4 = cv2.dilate(image_3, kernel, iterations=2)
# 对image_4进行中值滤波去除小白点
image_4 = cv2.medianBlur(image_4, 9)
# 保存膨胀后的图像
cv2.imwrite('image_4.jpg', image_4)

# 运用闭运算填充闭合区域
kernel = np.ones((100,100), np.uint8)
image_5 = cv2.morphologyEx(image_4, cv2.MORPH_CLOSE, kernel)
# 保存闭运算后的图像
cv2.imwrite('image_5.jpg', image_5)

# Canney边缘检测提取边缘
image_5 = cv2.imread('image_5.jpg', cv2.IMREAD_GRAYSCALE)
# 应用Canny边缘检测
image_6 = cv2.Canny(image_5, 200,200)
# 保存边缘检测结果
cv2.imwrite('image_6.jpg',image_6)

# 识别结果
# 读取原图和边缘检测后的图像
image_1 = cv2.imread('hanzi1.jpg')
image_6 = cv2.imread('image_6.jpg', cv2.IMREAD_GRAYSCALE)
# 寻找轮廓
contours, _ = cv2.findContours(image_6, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 在原图上画出轮廓
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(image_1, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 保存结果
cv2.imwrite('image_7.jpg', image_1)

# 展示结果
# 打开图片文件
img_0 = Image.open('hanzi1.jpg')
img_1 = Image.open('image_1.jpg')
img_2 = Image.open('image_2.jpg')
img_3 = Image.open('image_3.jpg')
img_4 = Image.open('image_4.jpg')
img_5 = Image.open('image_5.jpg')
img_6 = Image.open('image_6.jpg')
img_7 = Image.open('image_7.jpg')
# 计算所有图片的宽度和高度之和
total_width = sum([img.width for img in [img_0, img_1, img_2, img_3, img_4, img_5, img_6, img_7]])
max_height = max([img.height for img in [img_0, img_1, img_2, img_3, img_4, img_5, img_6, img_7]])
# 创建一个新的空白图片
result_img = Image.new('RGB', (total_width, max_height))
# 将每个图片粘贴到新图片上
x_offset = 0
for img in [img_0, img_1, img_2, img_3, img_4, img_5, img_6, img_7]:
    result_img.paste(img, (x_offset, 0))
    x_offset += img.width
# 显示结果图片
result_img.show()
# 保存结果图片
result_img.save('最终.jpg')
